/**
 * @filename:PurchaseOrderServiceImpl Mar 11, 2024
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.PageUtil;
import com.alibaba.druid.sql.PagerUtils;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.PurchaseDetailDao;
import com.wonder.app.mapper.PurchaseOrderDao;
import com.wonder.app.mapper.SynbdDao;
import com.wonder.app.service.KingdeeBasicService;
import com.wonder.app.service.PurchaseDetailService;
import com.wonder.app.service.PurchaseOrderService;
import com.wonder.app.request.PurchaseOrderRequest;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.DateUtils;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**   
 * @Description:TODO(采购订单服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class PurchaseOrderServiceImpl  extends ServiceImpl<PurchaseOrderDao, PurchaseOrder> implements PurchaseOrderService  {

	@Autowired
	private SynbdDao synbdDao;

	@Autowired
	private IVtuzxKingdeeService kingdeeService;

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private PurchaseDetailService purchaseDetailService;

	@Autowired
	private PurchaseDetailDao purchaseDetailDao;

	@Autowired
	private PurchaseOrderDao purchaseOrderDao;
    /**
     * 验证采购订单信息
     * 
     * @param purchaseOrder
     * @param type
     * @return String
     */
    @Override
    public String validate(PurchaseOrder purchaseOrder,String type){
    
    
       return "";
    }
    
    
    /**
	 * Description:采购订单分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<PurchaseOrder>   //分页记录
	 */
	@Override 
	public IPage<PurchaseOrder> selectList(PurchaseOrderRequest request, Page<PurchaseOrder> page){
	    LambdaQueryWrapper<PurchaseOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
	    if (null != request.getBillNo()) {
	       lambdaQueryWrapper.like(PurchaseOrder::getBillNo, request.getBillNo());
	      }
		if (null != request.getOrderNo()) {
			lambdaQueryWrapper.like(PurchaseOrder::getOrderNo, request.getOrderNo());
		}
		if (null != request.getCreateTime()){
			Date[] createTime = request.getCreateTime();
			if(createTime.length > 0)
				lambdaQueryWrapper.ge(PurchaseOrder::getCreateTime, createTime[0]);
			if(createTime.length == 2)
				lambdaQueryWrapper.le(PurchaseOrder::getCreateTime, DateUtils.dateToStr(createTime[1],"yyyy-MM-dd") + " 23:59:59");
		}
		lambdaQueryWrapper.orderByDesc(PurchaseOrder::getId);	
		Page<PurchaseOrder> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	@Override
	public void syncPurchaseOrder(String endTime) throws Exception {
		syncPurchaseOrder(0,50,endTime);
	}

	@Override
	public Map<String, Object> getDetail(String billNo) {
		PurchaseOrder purchaseOrder = purchaseOrderDao.selectOne(new QueryWrapper<PurchaseOrder>().eq("billNo", billNo));
		List<PurchaseDetail> purchaseDetailList = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetail>().eq("billNo", billNo));
		Map<String,Object> data = new HashMap<>();
		data.put("header",purchaseOrder);
		data.put("dataList",purchaseDetailList);
		return data;
	}

	@Override
	public Map<String, Object> getPurOrderList(int pageIndex, int pageSize,String orderNo) {

		LambdaQueryWrapper<PurchaseOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (!StringUtils.isEmpty(orderNo)){
			lambdaQueryWrapper.like(PurchaseOrder::getBillNo,orderNo);
		}
		Page<PurchaseOrder> page = new Page<>();
		page.setSize(pageSize);
		page.setCurrent(pageIndex);
		Page<PurchaseOrder> orderPage = purchaseOrderDao.selectPage(page, lambdaQueryWrapper);
		List<PurchaseOrder> purchaseOrderList = orderPage.getRecords();
		List<String> billNoList = new ArrayList<>();
		for (PurchaseOrder order : purchaseOrderList){
			String billNo = order.getBillNo();
			if (!billNoList.contains(billNo)){
				billNoList.add(billNo);
			}
		}
		LambdaQueryWrapper<PurchaseDetail> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(PurchaseDetail::getBillNo,billNoList);
		List<PurchaseDetail> purchaseDetailList = purchaseDetailDao.selectList(wrapper);
		for (PurchaseOrder order : purchaseOrderList){
			String billNo = order.getBillNo();
			for (PurchaseDetail detail : purchaseDetailList){
				String detailNo = detail.getBillNo();
				if (billNo.equals(detailNo)){
					if(null != order.getPurchaseDetail()){
						List<PurchaseDetail> purchaseDetail = order.getPurchaseDetail();
						purchaseDetail.add(detail);
						order.setPurchaseDetail(purchaseDetail);
					} else {
						List<PurchaseDetail> purchaseDetail = new ArrayList<>();
						purchaseDetail.add(detail);
						order.setPurchaseDetail(purchaseDetail);
					}

				}
			}
		}
		Map<String,Object> data = new HashMap<>();
		data.put("data",purchaseOrderList);
		return data;
	}


	/**
	 * 同步采购订单
	 * @param start
	 * @param limit
	 * @param endTime
	 */
	private void syncPurchaseOrder(int start,int limit,String endTime ) throws Exception{
		String cond = "";
		if (!VtuzxUtil.isEmpty(endTime)){
			cond = String.format("FCreateDate > '%s' or FModifyDate > '%s'",endTime,endTime);
		}
		VtuzxKingdeeCloudClient client = kingdeeService.loginKingdee();
		List<VtuzxMap> purchaseQuery = kingdeeService.query(client, "PUR_PurchaseOrder", new VtuzxArrayList<>(
						"FBillNo", //采购订单号
						"FContractNo", //合同单号
						"FCreateDate", //创建日期
						"FPurchaseDeptId", //采购部门
						"FPurchaserId", //采购员
						"FSupplierId.FName", //供应商
						"FSupplierId.FNumber", //供应商编码
						"FSettleId.FName", //结算方
						"FChargeId.FName", //收款方
						"FMaterialId.FNumber", //物料编码
						"FMaterialName", //物料名称
						"FModel", //规格
						"FUnitId.FName", //采购单位
						"Flot", //批号
						"FQty", //采购数量
						"FDeliveryDate", //交货日期
						"FPrice", //单价
						"FTaxPrice", //含税单价
						"FEntryDiscountRate", //折扣率(%)
						"FEntryAmount", //金额
						"FEntryTaxAmount", //税额
						"FTaxRate", //税率(%)
						"FBillAllAmount", //价税合计
						"FGiveAway",//是否赠品
						"F_DLMH_CGRKCK.FNumber",//仓库编号
						"F_DLMH_CGRKCK.FName",//仓库名称
						"FPOOrderEntry_FEntryID"//entryId

				),
				"", "", start, limit);

		List<PurchaseOrder> purchaseOrderList = new ArrayList<>();//存放到外层表的数据
		List<PurchaseDetail> purchaseDetailList = new ArrayList<>();//存放到详情表的数据
		for (VtuzxMap data : purchaseQuery){
			String purchaseNo = VtuzxUtil.getString(data,"FBillNo");//采购订单号
			String contractNo = VtuzxUtil.getString(data,"FContractNo");//合同单号
			String createStr = VtuzxUtil.getString(data,"FCreateDate");//创建日期
			Date createDate = DateUtils.strToDate(createStr,"yyyy-MM-dd'T'HH:mm:ss");
			String purchaseDepartId = VtuzxUtil.getString(data,"FPurchaseDeptId");//采购部门
			String purchaseId = VtuzxUtil.getString(data,"FPurchaserId");//采购员
			String FSupplierName = VtuzxUtil.getString(data,"FSupplierId.FName");//供应商名称
			String FSupplierNo = VtuzxUtil.getString(data,"FSupplierId.FNumber");//供应商编码
			String settle = VtuzxUtil.getString(data,"FSettleId.FName");//结算方
			String charge = VtuzxUtil.getString(data,"FChargeId.FName");//收款方
			String materialNo = VtuzxUtil.getString(data,"FMaterialId.FNumber");//物料编码
			String materialName = VtuzxUtil.getString(data,"FMaterialName");//物料名称
			String stockNo = VtuzxUtil.getString(data,"F_DLMH_CGRKCK.FNumber");//仓库编码
			String stockName = VtuzxUtil.getString(data,"F_DLMH_CGRKCK.FName");//仓库名称
			String model = VtuzxUtil.getString(data,"FModel");//规格
			String unit = VtuzxUtil.getString(data,"FUnitId.FName");//单位
			String batchNo = VtuzxUtil.getString(data,"Flot");//批号
			Integer entryId = VtuzxUtil.getInt(data,"FPOOrderEntry_FEntryID");//entryId
			double count = VtuzxUtil.getDouble(data,"FQty");//采购数量
			String deliveryStr = VtuzxUtil.getString(data,"FDeliveryDate");//交货日期
			Date deliveryDate = DateUtils.strToDate(deliveryStr,"yyyy-MM-dd'T'HH:mm:ss");
			double price = VtuzxUtil.getDouble(data,"FPrice");//单价
			double taxPrice = VtuzxUtil.getDouble(data,"FTaxPrice");//含税单价
			double discountRate = VtuzxUtil.getDouble(data,"FEntryDiscountRate");//折扣率
			double amount = VtuzxUtil.getDouble(data,"FEntryAmount");//金额
			double taxAmount = VtuzxUtil.getDouble(data,"FEntryTaxAmount");//税额
			double taxRate = VtuzxUtil.getDouble(data,"FEntryTaxAmount");//税率
			double FBillAllAmount  = VtuzxUtil.getDouble(data,"FBillAllAmount");//价税合计
			boolean giveAway  = VtuzxUtil.getBoolean(data,"FGiveAway");//价税合计
			//先判断外层表数据是否存在,如果存在就先删除之前的重新添加,不存在就直接添加
			PurchaseOrder purchaseOrder = purchaseOrderDao.selectOne(new QueryWrapper<PurchaseOrder>().eq("billNo", purchaseNo));
			if(null != purchaseOrder){//如果存在
				purchaseOrderDao.delete(new QueryWrapper<PurchaseOrder>().eq("billNo", purchaseNo));
				PurchaseOrder head = new PurchaseOrder();
				head.setBillNo(purchaseNo);
				head.setOrderNo(contractNo);
				head.setCreateTime(createDate);
				head.setPurchaseDeptName(purchaseDepartId);
				head.setPurchaseName(purchaseId);//采购员
				head.setSupplierName(FSupplierName);
				head.setSupplierNo(FSupplierNo);
				head.setSettle(settle);
				head.setCharge(charge);
				if (!purchaseOrderList.contains(head)){
					purchaseOrderList.add(head);
				}
			} else {
				PurchaseOrder head = new PurchaseOrder();
				head.setBillNo(purchaseNo);
				head.setOrderNo(contractNo);
				head.setCreateTime(createDate);
				head.setPurchaseDeptName(purchaseDepartId);
				head.setPurchaseName(purchaseId);//采购员
				head.setSupplierName(FSupplierName);
				head.setSupplierNo(FSupplierNo);
				head.setSettle(settle);
				head.setCharge(charge);
				if (!purchaseOrderList.contains(head)){
					purchaseOrderList.add(head);
				}
			}
			//查询内层数据是否存在
			List<PurchaseDetail> detailList = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetail>().eq("billNo", purchaseNo));
			//如果不为空删除详情表数据重新添加
			if (null != detailList){
				purchaseDetailDao.delete(new QueryWrapper<PurchaseDetail>().eq("billNo", purchaseNo));
				PurchaseDetail detail = new PurchaseDetail();
				detail.setEntryId(entryId);
				detail.setMaterialNo(materialNo);
				detail.setMaterialName(materialName);
				detail.setSpecification(model);
				detail.setUnit(unit);
				detail.setBatchNo(batchNo);
				detail.setCount(count);
				detail.setDeliveryDate(deliveryDate);
				detail.setPrice(price);
				detail.setTaxPrice(taxPrice);
				detail.setStockNo(stockNo);
				detail.setStockName(stockName);
				detail.setDiscountRate(discountRate);
				detail.setBillAmount(amount);
				detail.setTaxAmount(taxAmount);
				detail.setEntryTaxRate(taxRate);
				detail.setBillAllAmount(FBillAllAmount);
				detail.setGiveAway(giveAway);
				detail.setBillNo(purchaseNo);
				if (!purchaseDetailList.contains(detail)){
					purchaseDetailList.add(detail);
				}
			} else {
				PurchaseDetail detail = new PurchaseDetail();
				detail.setEntryId(entryId);
				detail.setMaterialNo(materialNo);
				detail.setMaterialName(materialName);
				detail.setSpecification(model);
				detail.setUnit(unit);
				detail.setBatchNo(batchNo);
				detail.setCount(count);
				detail.setDeliveryDate(deliveryDate);
				detail.setPrice(price);
				detail.setTaxPrice(taxPrice);
				detail.setDiscountRate(discountRate);
				detail.setBillAmount(amount);
				detail.setTaxAmount(taxAmount);
				detail.setEntryTaxRate(taxRate);
				detail.setBillAllAmount(FBillAllAmount);
				detail.setGiveAway(giveAway);
				detail.setBillNo(purchaseNo);
				detail.setStockNo(stockNo);
				detail.setStockName(stockName);
				if (!purchaseDetailList.contains(detail)){
					purchaseDetailList.add(detail);
				}
			}
		}

		//添加外层表数据
		purchaseOrderService.saveBatch(purchaseOrderList);
		//添加详情表数据
		purchaseDetailService.saveBatch(purchaseDetailList);

		if (purchaseQuery.size() >= limit) {
			syncPurchaseOrder(start + limit, limit,endTime);
		}
	}
}